<template>
  <div>
    <!-- 地址管理 -->
    <div
      class="bg-white h-2/3 w-1/3 fixed top-1/2 left-1/2 translate-[-50%] -translate-y-1/2 z-50 max-w-4xlmax-h-[90vh] overflow-y-auto shadow-2xl rounded-lg">
      <!-- 头部标题区域 -->
      <div class="border-b px-6 py-4 flex justify-between items-center">
        <h2 class="text-xl font-bold text-gray-800">地址管理</h2>
        <button class="text-gray-500 hover:text-gray-800 transition-colors cursor-pointer" id="closeAddressModal"
          @click="$emit('hidden')">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 新增地址按钮 -->
      <div class="px-6 py-4">
        <button
          class="cursor-pointer w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2"
          id="addNewAddress" @click="handlerAdd">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
          </svg>
          <span>新增收货地址</span>
        </button>
      </div>

      <!-- 地址列表区域 -->
      <div class="px-6 h-3/4 overflow-auto space-y-4 " id="addressList">
        <!-- 地址项1 - 默认地址 -->
        <div v-for="(item, index) in addressList" :key="index"
          class="border border-gray-200 rounded-lg p-4 relative hover:border-blue-500 transition-colors">
          <div class="absolute top-4 left-4 bg-blue-100 text-blue-600 text-xs px-2 py-1 rounded"
            v-show="item.isDefault == 1">
            默认地址
          </div>
          <div :class="`${item.isDefault == 1 ? 'mt-8' : ''}`">
            <div class="flex justify-between items-start">
              <h3 class="font-medium text-gray-900">{{ item.receiverName }}</h3>
              <div class="flex gap-2">
                <button class="text-gray-500 hover:text-blue-600 transition-colors text-sm edit-address cursor-pointer"
                  @click="handlerEdit(item)">编辑</button>

                <el-popconfirm :title="`你确定要删除该地址吗`" width="200px" @confirm="deleteUser(item.addressId)">
                  <template #reference>
                    <button
                      class="text-gray-500 hover:text-red-600 transition-colors text-sm delete-address cursor-pointer">删除</button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
            <p class="text-gray-600 mt-1">{{ item.receiverPhone }}</p>
            <p class="text-gray-600 mt-2">{{ item.province }} {{ item.city }} {{ item.district }} {{
              item.detailAddress }}</p>
          </div>
        </div>
      </div>

      <!-- 新增/编辑地址表单 (默认隐藏) -->
      <div v-show="formShow"
        class="px-6 py-4 fixed top-1/2 left-1/2 translate-[-50%] -translate-y-1/2 bg-white shadow-2xl border"
        id="addressForm">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold text-gray-800" id="formTitle">{{ formType == 'add' ? '新增' : '修改' }}收货地址</h3>
          <button class="text-gray-500 hover:text-gray-800 transition-colors" id="cancelForm" @click="formShow = false">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24"
              stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <form id="addressFormElement">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">收件人</label>
              <input type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入收件人姓名" v-model="formData.receiverName">
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">手机号码</label>
              <input type="tel"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="请输入手机号码" v-model="formData.receiverPhone">
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">所在地区</label>
              <div class="grid grid-cols-3 gap-3">
                <el-input type="text" placeholder="省份" v-model="formData.province" />
                <el-input type="text" placeholder=“城市 v-model="formData.city" />
                <el-input type="text" placeholder="地区" v-model="formData.district" />
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">详细地址</label>
              <textarea
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                rows="3" placeholder="请输入详细地址，如街道、门牌号等" v-model="formData.detailAddress"></textarea>
            </div>

            <div class="flex items-center">
              <el-checkbox label="设为默认地址" v-model="formData.isDefault" :true-value="1" :false-value="0"></el-checkbox>
            </div>

            <div class="pt-4 flex gap-3">
              <button type="button"
                class="flex-1 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                id="backToList" @click="formShow = false">返回列表</button>
              <button type="submit"
                class="flex-1 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                @click="confirm">保存地址</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div class="fixed inset-0 bg-black opacity-50 z-40"></div>
  </div>
</template>

<script setup>
import { addAddressApi, deleteAddressApi, getAddressApi, updateAddressApi } from '@/apis/address';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watchEffect } from 'vue';
const formType = ref('add')
const addressList = ref([])
let formShow = ref(false)
let formData = ref({
  "addressId": '',
  "userId": '',
  "receiverName": "",
  "receiverPhone": "",
  "province": "",
  "city": "",
  "district": "",
  "detailAddress": "",
  "isDefault": ""
})

const getAddress = async () => {
  try {
    let res = await getAddressApi()
    addressList.value = res.data
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}
const userId = localStorage.getItem('userId')
const handlerAdd = () => {
  formShow.value = true
  formType.value = 'add'
  formData.value = {
    "addressId": '',
    userId,
    "receiverName": "",
    "receiverPhone": "",
    "province": "",
    "city": "",
    "district": "",
    "detailAddress": "",
    "isDefault": 0
  }
}
const handlerEdit = (item) => {
  formShow.value = true
  formType.value = 'edit'
  formData.value = { ...item, userId }
}

const confirm = async () => {
  if (!formData.value.addressId) {
    try {
      await addAddressApi(formData.value)
      ElMessage.success('新增成功');
      getAddress()
      formShow.value = false;
    } catch (error) {
      console.log(error)
      ElMessage.error('新增失败');
      formShow.value = false;
    }
  } else {
    try {
      await updateAddressApi(formData.value)
      ElMessage.success('修改成功');
      getAddress()
      formShow.value = false;
    } catch (error) {
      ElMessage.success('修改失败');
      formShow.value = false;
    }
  }
}

const deleteUser = async (id) => {
  try {
    await deleteAddressApi(id)
    ElMessage.success('删除成功');
    getAddress()
  } catch (error) {
    ElMessage.error('删除数据失败');
  }
}
onMounted(() => {
  getAddress()
})

</script>

<style lang="scss" scoped></style>